<template>
  <div class="dcy-content">
    <!-- 查询条件 -->
    <Form ref="queryParams" :model="queryParams" inline :label-width="60" label-position="left">
      <FormItem label="用户名">
        <Input type="text" v-model="queryParams.username" clearable placeholder="请输入用户名"/>
      </FormItem>
      <FormItem :label-width="0" class="search-btn-mar">
        <Button icon="md-search" type="primary" @click="refresh()">查询</Button>
        <Button icon="md-refresh" type="primary" @click="reset()">重置</Button>
        <Button icon="md-add" type="primary" @click="addUser()">添加</Button>
        <Button icon="md-add" type="primary" @click="removeBatch()" :disabled="delBtnDisabled">删除</Button>
      </FormItem>
    </Form>

    <!-- 表格 -->
    <dcy-table
      ref="dcyTable"
      unique-id="userId"
      :query-params="queryParams"
      :url="url"
      @table-select-val="selectVal"
      :columns="columns">
      <template slot-scope="{ row, index }" slot="sex">
        <Tag color="blue" v-if="row.sex === '0'">男</Tag>
        <Tag color="green" v-if="row.sex === '1'">女</Tag>
      </template>
      <template slot-scope="{ row, index }" slot="userStatus">
        <Tag color="success" v-if="row.userStatus === '0'">正常</Tag>
        <Tag color="error" v-if="row.userStatus === '1'">禁用</Tag>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <a @click="update(row)">修改</a>
        <Divider type="vertical"/>
        <a @click="remove(row)">删除</a>
        <Divider type="vertical"/>
        <a @click="resetPassword(row)">重置密码</a>
        <Divider type="vertical"/>
        <a @click="authRole(row)">授权角色</a>
        <Divider type="vertical"/>
        <a @click="authGroup(row)">授权用户组</a>
      </template>
    </dcy-table>

    <!-- 添加表单 -->
    <Modal
      v-model="dialogShow"
      :title="dialogTitle"
      :mask-closable="false"
      @on-cancel="handleReset('form')">
      <Form ref="form" :model="form" :rules="rules" :label-width="80">
        <FormItem label="用户名" prop="username">
          <Input v-model="form.username" placeholder="请输入用户名"></Input>
        </FormItem>
        <FormItem label="密码" prop="password" v-if="dialogTitle === '添加用户'">
          <Input v-model="form.password" type="password" placeholder="请输入密码"></Input>
        </FormItem>
        <FormItem label="确认密码" prop="passwordCheck" v-if="dialogTitle === '添加用户'">
          <Input type="password" v-model="form.passwordCheck" placeholder="请输入确认密码"></Input>
        </FormItem>
        <FormItem label="昵称" prop="nickName">
          <Input v-model="form.nickName" placeholder="请输入昵称"></Input>
        </FormItem>
        <FormItem label="性别" prop="sex">
          <Select v-model="form.sex" placeholder="请选择性别">
            <template v-for="item in sexOptionList">
              <Option :value="item.dictValue">{{item.dictLable}}</Option>
            </template>
          </Select>
        </FormItem>
        <FormItem label="状态" prop="userStatus">
          <Select v-model="form.userStatus" placeholder="请选择状态">
            <template v-for="item in statusOptionList">
              <Option :value="item.dictValue">{{item.dictLable}}</Option>
            </template>
          </Select>
        </FormItem>
        <FormItem label="邮箱" prop="email">
          <Input v-model="form.email" placeholder="请输入邮箱"></Input>
        </FormItem>
        <FormItem label="手机号" prop="phoneNumber">
          <Input v-model="form.phoneNumber" placeholder="请输入手机号"></Input>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
        </FormItem>
      </Form>
      <!-- 自定义按钮组 -->
      <div slot="footer">
        <Button type="text"  @click="handleReset('form')">取消</Button>
        <Button type="primary"  @click="handleSubmit('form')">确认</Button>
      </div>
    </Modal>

    <!-- 授权角色-->
    <Modal
      v-model="dialogAuthRoleShow"
      title="授权角色"
      :mask-closable="false"
      @on-ok="saveAuthRole"
      @on-cancel="cancelAuthRoleDialog">
      <Transfer
        v-if="dialogAuthRoleShow"
        filterable
        :data="roleList"
        :titles="['角色列表','已授权角色']"
        :target-keys="targetKeys"
        :filter-method="filterMethod"
        @on-change="handleRoleChange"></Transfer>
    </Modal>

    <!-- 授权用户组-->
    <Modal
      v-model="dialogAuthGroupShow"
      title="授权用户组"
      :mask-closable="false"
      @on-ok="saveAuthGroup"
      @on-cancel="cancelAuthGroupDialog">
      <Transfer
        v-if="dialogAuthGroupShow"
        filterable
        :data="groupList"
        :titles="['用户组列表','已授权用户组']"
        :target-keys="targetGroupKeys"
        :filter-method="filterMethod"
        @on-change="handleGroupChange"></Transfer>
    </Modal>

  </div>
</template>

<script>
    import DcyTable from '../../components/dcy/dcy-table'
    import {
        addUserInfo,
        deleteBatchUserInfoById,
        deleteUserInfoById, getAuthGroupListByUserId, getAuthRoleListByUserId, getUserInfoByUsername,
        resetPassword, saveAuthGroup, saveAuthRole,
        updateUserInfo
    } from '../../api/admin/user'
    import {noticeError, noticeSuccess} from '../../libs/notice'
    import {getRoleAllList} from "../../api/admin/role";
    import {getGroupAllList} from "../../api/admin/group";
    import {getDictByType} from "../../api/common";

    export default {
        name: 'user-manage',
        components: {DcyTable},
        data() {
            const validateUsernameCount = (rule, value, callback) => {
                if (value !== '') {
                    getUserInfoByUsername(this.form.username).then(res=>{
                        if (res.data !== null){
                            if (this.form.userId === res.data.userId){
                                callback()
                            }else{
                                callback(new Error('用户名重复，请重新输入'))
                            }
                        }else{
                            callback()
                        }
                    })
                } else {
                    callback()
                }
            };
            const validatePassCheck = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入确认密码'))
                } else if (value !== this.form.password) {
                    callback(new Error('两次密码不一致，请重新输入'))
                } else {
                    callback()
                }
            };
            return {
                url: '/admin-service/user/page',
                columns: [
                    {title: '用户名', key: 'username', align: 'center', sortable: true},
                    {title: '昵称', key: 'nickName', align: 'center'},
                    {title: '邮箱', key: 'email', align: 'center'},
                    {title: '手机号码', key: 'phoneNumber', align: 'center'},
                    {title: '性别', slot: 'sex', align: 'center'},
                    {title: '状态', slot: 'userStatus', align: 'center'},
                    {title: '操作', slot: 'action', align: 'center', width: 400}
                ],
                queryParams: {},
                dialogShow: false,
                dialogAuthRoleShow: false,
                dialogAuthGroupShow: false,
                delBtnDisabled: true,
                ids: [],
                dialogTitle: '添加用户',
                form: {},
                rules: {
                    username: [
                        this.$ruler('用户名'),
                        {type: 'string', max: 16, min: 6, message: '请输入6-16个字符', trigger: 'blur'},
                        {validator: validateUsernameCount, trigger: 'blur'}
                    ],
                    password: [
                        this.$ruler('密码'),
                        {type: 'string', max: 16, min: 6, message: '请输入6-16个字符', trigger: 'blur'}
                    ],
                    passwordCheck: [
                        this.$ruler('确认密码'),
                        {validator: validatePassCheck, trigger: 'blur'}
                    ],
                    nickName: [
                        this.$ruler('昵称')
                    ],
                    sex: [
                        this.$ruler('性别', 'change')
                    ],
                    userStatus: [
                        this.$ruler('状态', 'change')
                    ],
                    phoneNumber: [
                        this.$ruler('手机号')
                    ]
                },
                // 授权角色使用
                userId: null,
                roleList: [],
                targetKeys: [],
                // 授权用户组
                groupList: [],
                targetGroupKeys: [],
                sexOptionList:[],
                statusOptionList:[],
            }
        },
        methods: {
            /**
             * 刷新
             */
            refresh() {
                // 清空选中状态
                this.$refs.dcyTable.selectAll(false);
                this.$refs.dcyTable.refresh()
            },
            /**
             * 重置搜索条件
             */
            reset() {
                this.queryParams = {}
            },
            /**
             * 修改弹出框
             * @param row
             */
            update(row) {
                this.form = {...row};
                this.dialogTitle = '修改用户';
                this.dialogShow = true;
            },
            /**
             * 添加弹出框
             */
            addUser() {
                this.form.password = null;
                this.form.userType = 1;
                this.dialogTitle = '添加用户';
                this.dialogShow = true;
            },
            /**
             * 批量删除
             */
            removeBatch() {
                this.$Modal.confirm({
                    title: '您确认删除所选内容吗？',
                    onOk: () => {
                        deleteBatchUserInfoById(this.ids).then(res => {
                            if (res.data) {
                                noticeSuccess('del')
                            } else {
                                noticeError('del')
                            }
                            this.refresh()
                        })
                    }
                })
            },
            /**
             * 提交表单
             * @param name
             */
            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        if (this.dialogTitle === '添加用户') {
                            addUserInfo(this.form).then(res => {
                                if (res.data) {
                                    noticeSuccess('add')
                                } else {
                                    noticeError('add')
                                }
                                this.cancelDialogAndRefresh()
                            })
                        } else {
                            updateUserInfo(this.form).then(res => {
                                if (res.data) {
                                    noticeSuccess('upd')
                                } else {
                                    noticeError('upd')
                                }
                                this.cancelDialogAndRefresh()
                            })
                        }
                    }
                })
            },
            /**
             * 行内删除
             * @param row
             */
            remove(row) {
                this.$Modal.confirm({
                    title: '您确认删除这条内容吗？',
                    onOk: () => {
                        deleteUserInfoById(row.userId).then(res => {
                            if (res.data) {
                                noticeSuccess('del')
                            } else {
                                noticeError('del')
                            }
                            // 刷新表格
                            this.refresh()
                        })
                    }
                })
            },
            /**
             * 重置表单
             * @param name
             */
            handleReset(name) {
                this.form = {};
                this.dialogShow = false;
                this.$refs[name].resetFields()
            },
            /**
             * 关闭弹出框 和 刷新表格
             */
            cancelDialogAndRefresh() {
                // 清空表单
                this.handleReset('form');
                // 刷新表格
                this.refresh()
            },
            /**
             * 点击每一行的checkbox
             */
            selectVal(ids) {
                this.ids = ids;
                this.delBtnDisabled = !this.ids.length
            },
            /**
             * 重置密码
             * @param row
             */
            resetPassword(row) {
                this.$Modal.confirm({
                    title: '重置密码',
                    content: '确定重置密码123456吗？',
                    onOk: () => {
                        row.password = '123456';
                        resetPassword(row).then(res => {
                            if (res.data) {
                                noticeSuccess('upd')
                            } else {
                                noticeError('upd')
                            }
                            // 刷新表格
                            this.refresh()
                        })
                    }
                });
            },
            /**
             * 关闭授权角色弹出框
             */
            cancelAuthRoleDialog() {
                this.dialogAuthRoleShow = false;
            },
            cancelAuthGroupDialog() {
                this.dialogAuthGroupShow = false;
            },
            handleRoleChange(newTargetKeys) {
                this.targetKeys = newTargetKeys;
            },
            filterMethod(data, query){
                return data.label.indexOf(query) > -1;
            },
            handleGroupChange(newTargetKeys) {
                this.targetGroupKeys = newTargetKeys;
            },
            /**
             * 授权角色
             * @param row
             */
            authRole(row) {
                this.userId = row.userId;
                getRoleAllList().then(res => {
                    if (res.success) {
                        let roleList = [];
                        res.data.forEach(e => {
                            let role = {
                                key: e.roleId,
                                label: e.roleName,
                                disabled: e.roleStatus === '1'
                            };
                            roleList.push(role);
                        });
                        this.roleList = roleList;
                    }
                });
                getAuthRoleListByUserId(this.userId).then(res => {
                    this.targetKeys = res.data.map(e => e.roleId);
                })
                this.dialogAuthRoleShow = true;
            },
            /**
             * 保存授权角色
             */
            saveAuthRole() {
                let userInfoRoleDTO = {
                    userId: this.userId,
                    roleIds: this.targetKeys
                };
                saveAuthRole(userInfoRoleDTO).then(res => {
                    if (res.data) {
                        noticeSuccess('d')
                    } else {
                        noticeError('d')
                    }
                    // 刷新表格
                    this.refresh()
                })
            },
            /**
             * 授权用户组
             * @param row
             */
            authGroup(row) {
                this.userId = row.userId;
                getGroupAllList().then(res => {
                    if (res.success) {
                        let groupList = [];
                        res.data.forEach(e => {
                            let group = {
                                key: e.userGroupId,
                                label: e.userGroupName
                            };
                            groupList.push(group);
                        });
                        this.groupList = groupList;
                    }
                });
                getAuthGroupListByUserId(this.userId).then(res => {
                    this.targetGroupKeys = res.data.map(e => e.userGroupId);
                })
                this.dialogAuthGroupShow = true;
            },
            /**
             * 保存授权用户组
             */
            saveAuthGroup() {
                let userInfoGroupDTO = {
                    userId: this.userId,
                    userGroupIds: this.targetGroupKeys
                };
                saveAuthGroup(userInfoGroupDTO).then(res => {
                    if (res.data) {
                        noticeSuccess('d')
                    } else {
                        noticeError('d')
                    }
                    // 刷新表格
                    this.refresh()
                })
            },
        },
        mounted() {
            getDictByType('sex').then(res=>{
                this.sexOptionList = res.data;
            });
            getDictByType('status').then(res=>{
                this.statusOptionList = res.data;
            })
        }
    }
</script>

<style scoped>

</style>
